package com.enlf.controller.admin;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enlf.dto.R;
import com.enlf.dto.VoucherOrderDTO;
import com.enlf.entity.Shop;
import com.enlf.entity.User;
import com.enlf.entity.Voucher;
import com.enlf.entity.VoucherOrder;
import com.enlf.service.IShopService;
import com.enlf.service.IUserService;
import com.enlf.service.IVoucherOrderService;
import com.enlf.service.IVoucherService;
import com.enlf.utils.EnlfConstants;
import com.enlf.utils.SystemConstants;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author renge
 * @since 2023-9-11
 */
@RestController
@RequestMapping("/admin/order")
public class AdminVoucherOrderController {
    @Resource
    private IVoucherOrderService voucherOrderService;
    @Resource
    private IShopService iShopService;
    @Resource
    private IUserService iUserService;
    @Resource
    private IVoucherService voucherService;

    public static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    /**
     * 分页查询订单信息
     * @param current 页码
     * @return 商铺列表
     */
    @GetMapping("/list")
    public R queryVoucherOrderList(
            @RequestParam(value = "current", defaultValue = "1") Integer current
    ) {
        // 根据类型分页查询
        Page<VoucherOrder> page = voucherOrderService.query()
                .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE_FIVE));
        List<VoucherOrderDTO> voucherOrderList= page.getRecords().stream().map(order -> {
            VoucherOrderDTO voucherOrder = BeanUtil.copyProperties(order, VoucherOrderDTO.class);
            User user = iUserService.getById(order.getUserId());
            Voucher voucher = voucherService.getById(order.getVoucherId());
            Shop shop = iShopService.getById(voucher.getShopId());
            voucherOrder
                    .setNickName(user.getNickName()).setShopName(shop.getName());
            voucherOrder.setOrderId(voucherOrder.getId().toString());
            voucherOrder.setTitle(voucher.getTitle());
            voucherOrder.setRules(voucher.getRules());
            voucherOrder.setPayValue(voucher.getPayValue());
            voucherOrder.setActualValue(voucher.getActualValue());
            voucherOrder.setPayTime(handleTime(order.getPayTime()));
            voucherOrder.setUseTime(handleTime(order.getUseTime()));
            voucherOrder.setRefundTime(handleTime(order.getRefundTime()));
            return voucherOrder;
        }).collect(Collectors.toList());
        // 返回数据
        Map<String,Object> result = new HashMap<>();
        result.put("total",page.getTotal());
        result.put("list",voucherOrderList);

        return R.OK(result);
    }

    @GetMapping("/list/order")
    public R queryVoucherOrder(
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "id", required = false) Integer id,
            @RequestParam(value = "current", defaultValue = "1") Integer current){
        Page<VoucherOrder> page = null;
        if (null != userId){
            // 根据类型分页查询
            page = voucherOrderService.query().eq("user_id",userId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE_FIVE));
        }
        else if (null != id){
            page = voucherOrderService.query().eq("id",id)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE_FIVE));
        }else {
            // 如果两者都没有提供，则返回空的分页结果
            page = new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE_FIVE);
        }

        List<VoucherOrderDTO> voucherOrderList= page.getRecords().stream().map(order -> {
            VoucherOrderDTO voucherOrder = BeanUtil.copyProperties(order, VoucherOrderDTO.class);
            User user = iUserService.getById(order.getUserId());
            Voucher voucher = voucherService.getById(order.getVoucherId());
            Shop shop = iShopService.getById(voucher.getShopId());
            voucherOrder
                    .setNickName(user.getNickName()).setShopName(shop.getName());
            voucherOrder.setTitle(voucher.getTitle());
            voucherOrder.setRules(voucher.getRules());
            voucherOrder.setPayValue(voucher.getPayValue());
            voucherOrder.setActualValue(voucher.getActualValue());
            voucherOrder.setPayTime(handleTime(order.getPayTime()));
            voucherOrder.setUseTime(handleTime(order.getUseTime()));
            voucherOrder.setRefundTime(handleTime(order.getRefundTime()));
            return voucherOrder;
        }).collect(Collectors.toList());
        Map<String,Object> result = new HashMap<>();
        result.put("total",page.getTotal());
        result.put("list",voucherOrderList);
        return R.OK(result);
    }
    @PutMapping("update")
    public R updateOrder(@RequestParam(value = "orderId", required = false) String orderId,
                         @RequestParam(value = "status", required = false) String status){
        VoucherOrder voucherOrder = voucherOrderService.getById(orderId);
        if (null == voucherOrder){
            return R.FAIL("订单不存在");
        }
        voucherOrder.setStatus(Integer.valueOf(status));
        voucherOrder.setUpdateTime(LocalDateTime.now());
        if (EnlfConstants.ENLF_NUM_2.equals(status)){
            //未支付 -> 支付
            if (EnlfConstants.ENLF_NUM_1.equals(voucherOrder.getStatus())){
                voucherOrder.setPayTime(LocalDateTime.now());
            }
            //未支付 -> 取消
            if (EnlfConstants.ENLF_NUM_4.equals(voucherOrder.getStatus())){
                voucherOrder.setRefundTime(LocalDateTime.now());
            }
        }
        //已支付 -> 核销
        if (EnlfConstants.ENLF_NUM_3.equals(status)){
            voucherOrder.setUseTime(LocalDateTime.now());
        }
        //已支付 -> 待退款
        if (EnlfConstants.ENLF_NUM_5.equals(status)){
            voucherOrder.setRefundTime(LocalDateTime.now());
        }
        //待退款 -> 退款
        if (EnlfConstants.ENLF_NUM_6.equals(status)){
            voucherOrder.setRefundTime(LocalDateTime.now());
        }
        voucherOrderService.updateById(voucherOrder);
        return R.OK();
    }

    public String handleTime(LocalDateTime time){
        if (null == time){
            return null;
        }
        return time.format(formatter);

    }
}
